package com.shuo.juc.bucket;

import com.google.common.util.concurrent.RateLimiter;

/**
 * RateLimiter通过限制后面请求的等待时间，来支持一定程度的突发请求(预消费透支)
 */
public class RateLimiterTest {
    public static void main(String[] args) {
        // 每秒create的令牌数
        RateLimiter rateLimiter = RateLimiter.create(2);
        sleeping(1);
        // 阻塞0s, 透支5个令牌
        System.out.println(rateLimiter.acquire(5));
        // 阻塞2.5s, 这段时间是用来补透支的5个令牌; 然后再透支2个令牌
        System.out.println(rateLimiter.acquire(2));
        // 阻塞1s, 这段时间是用来补透支的2个令牌; 然后再透支1个令牌
        System.out.println(rateLimiter.acquire(1));
    }

    private static void sleeping(int sec) {
        try {
            Thread.sleep(sec * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
